from app.models import Base, engine, get_db
import app.models.user  # 导入用户模型
import app.models.role  # 导入角色模型
import app.models.permission  # 导入权限模型
from app.services.user_service import UserService
from app.services.role_service import RoleService
from app.services.permission_service import PermissionService

def init_database():
    """初始化数据库，先删除存在的表再重新创建所有定义的表"""
    print("开始创建数据库表...")
    print("先删除现有表结构...")
    Base.metadata.drop_all(bind=engine)
    print("开始创建新表结构...")
    Base.metadata.create_all(bind=engine)
    print("数据库表创建完成！")

def init_data():
    """初始化系统基础数据"""
    print("开始初始化基础数据...")
    db = next(get_db())
    try:
        # 创建默认角色
        admin_role = None
        user_role = None
        operator_role = None
        
        if not db.query(app.models.role.Role).filter_by(code="ROLE_ADMIN").first():
            admin_role = RoleService.create_role(
                db, name="管理员", code="ROLE_ADMIN", 
                description="系统管理员，拥有所有权限"
            )
            print(f"\t创建角色: {admin_role.name}")
        else:
            admin_role = db.query(app.models.role.Role).filter_by(code="ROLE_ADMIN").first()
        
        if not db.query(app.models.role.Role).filter_by(code="ROLE_USER").first():
            user_role = RoleService.create_role(
                db, name="普通用户", code="ROLE_USER", 
                description="普通用户，拥有基本权限"
            )
            print(f"\t创建角色: {user_role.name}")
        else:
            user_role = db.query(app.models.role.Role).filter_by(code="ROLE_USER").first()
            
        if not db.query(app.models.role.Role).filter_by(code="ROLE_OPERATOR").first():
            operator_role = RoleService.create_role(
                db, name="运维人员", code="ROLE_OPERATOR", 
                description="运维人员，拥有系统维护权限"
            )
            print(f"\t创建角色: {operator_role.name}")
        else:
            operator_role = db.query(app.models.role.Role).filter_by(code="ROLE_OPERATOR").first()
            
        # 初始化权限
        init_permissions(db, admin_role, user_role, operator_role)
            
        # 创建默认管理员账号
        admin_user = db.query(app.models.user.User).filter_by(username="admin").first()
        if not admin_user:
            admin_user = UserService.create_user(
                db, username="admin", email="admin@example.com", password="admin123"
            )
            print(f"\t创建用户: {admin_user.username}")
            
            # 获取管理员角色
            if not admin_role:
                admin_role = db.query(app.models.role.Role).filter_by(code="ROLE_ADMIN").first()
                
            # 给管理员分配角色
            if admin_role:
                RoleService.assign_role_to_user(db, admin_user.id, admin_role.id)
                print(f"\t用户 {admin_user.username} 分配角色: {admin_role.name}")
        
        print("基础数据初始化完成！")
    except Exception as e:
        db.rollback()
        print(f"初始化数据失败: {str(e)}")
    finally:
        db.close()

def init_permissions(db, admin_role, user_role, operator_role):
    """初始化权限数据和权限树"""
    print("开始初始化权限数据...")
    
    # 创建权限树结构
    # 1. 系统管理
    system_manage = create_permission_if_not_exists(
        db, name="系统管理", code="system", is_menu=True, 
        path="/system", icon="setting", sort_order=1
    )
    
    # 1.1 用户管理
    user_manage = create_permission_if_not_exists(
        db, name="用户管理", code="system:user", parent_id=system_manage.id, 
        is_menu=True, path="/system/user", component="system/user/index", 
        icon="user", sort_order=1
    )
    
    # 用户管理权限
    create_permission_if_not_exists(
        db, name="用户查询", code="system:user:query", parent_id=user_manage.id, sort_order=1
    )
    
    create_permission_if_not_exists(
        db, name="用户新增", code="system:user:create", parent_id=user_manage.id, sort_order=2
    )
    
    create_permission_if_not_exists(
        db, name="用户修改", code="system:user:update", parent_id=user_manage.id, sort_order=3
    )
    
    create_permission_if_not_exists(
        db, name="用户删除", code="system:user:delete", parent_id=user_manage.id, sort_order=4
    )
    
    # 1.2 角色管理
    role_manage = create_permission_if_not_exists(
        db, name="角色管理", code="system:role", parent_id=system_manage.id, 
        is_menu=True, path="/system/role", component="system/role/index", 
        icon="peoples", sort_order=2
    )
    
    # 角色管理权限
    create_permission_if_not_exists(
        db, name="角色查询", code="system:role:query", parent_id=role_manage.id, sort_order=1
    )
    
    create_permission_if_not_exists(
        db, name="角色新增", code="system:role:create", parent_id=role_manage.id, sort_order=2
    )
    
    create_permission_if_not_exists(
        db, name="角色修改", code="system:role:update", parent_id=role_manage.id, sort_order=3
    )
    
    create_permission_if_not_exists(
        db, name="角色删除", code="system:role:delete", parent_id=role_manage.id, sort_order=4
    )
    
    create_permission_if_not_exists(
        db, name="角色授权", code="system:role:assign", parent_id=role_manage.id, sort_order=5
    )
    
    # 1.3 权限管理
    perm_manage = create_permission_if_not_exists(
        db, name="权限管理", code="system:permission", parent_id=system_manage.id, 
        is_menu=True, path="/system/permission", component="system/permission/index", 
        icon="lock", sort_order=3
    )
    
    # 权限管理权限
    create_permission_if_not_exists(
        db, name="权限查询", code="system:permission:query", parent_id=perm_manage.id, sort_order=1
    )
    
    create_permission_if_not_exists(
        db, name="权限新增", code="system:permission:create", parent_id=perm_manage.id, sort_order=2
    )
    
    create_permission_if_not_exists(
        db, name="权限修改", code="system:permission:update", parent_id=perm_manage.id, sort_order=3
    )
    
    create_permission_if_not_exists(
        db, name="权限删除", code="system:permission:delete", parent_id=perm_manage.id, sort_order=4
    )
    
    # 2. 系统监控
    monitor = create_permission_if_not_exists(
        db, name="系统监控", code="monitor", is_menu=True,
        path="/monitor", icon="monitor", sort_order=2
    )
    
    # 2.1 在线用户
    online_user = create_permission_if_not_exists(
        db, name="在线用户", code="monitor:online", parent_id=monitor.id,
        is_menu=True, path="/monitor/online", component="monitor/online/index", 
        icon="online", sort_order=1
    )
    
    create_permission_if_not_exists(
        db, name="在线用户查询", code="monitor:online:query", parent_id=online_user.id, sort_order=1
    )
    
    create_permission_if_not_exists(
        db, name="批量强退", code="monitor:online:batchLogout", parent_id=online_user.id, sort_order=2
    )
    
    create_permission_if_not_exists(
        db, name="单条强退", code="monitor:online:logout", parent_id=online_user.id, sort_order=3
    )
    
    # 2.2 系统日志
    sys_log = create_permission_if_not_exists(
        db, name="系统日志", code="monitor:log", parent_id=monitor.id, 
        is_menu=True, path="/monitor/log", component="monitor/log/index", 
        icon="log", sort_order=2
    )
    
    create_permission_if_not_exists(
        db, name="操作日志查询", code="monitor:log:query", parent_id=sys_log.id, sort_order=1
    )
    
    create_permission_if_not_exists(
        db, name="操作日志删除", code="monitor:log:delete", parent_id=sys_log.id, sort_order=2
    )
    
    # 为管理员角色分配所有权限
    assign_all_permissions_to_admin(db, admin_role.id)
    
    # 为普通用户和运维人员分配基本权限
    assign_basic_permissions(db, user_role.id, operator_role.id)
    
    print("权限数据初始化完成！")

def create_permission_if_not_exists(db, **kwargs):
    """如果权限不存在则创建"""
    code = kwargs.get('code')
    permission = db.query(app.models.permission.Permission).filter_by(code=code).first()
    if not permission:
        permission = PermissionService.create_permission(db, **kwargs)
        print(f"\t创建权限: {permission.name}")
    return permission

def assign_all_permissions_to_admin(db, admin_role_id):
    """为管理员角色分配所有权限"""
    # 获取所有权限
    permissions = db.query(app.models.permission.Permission).all()
    
    # 获取管理员角色已有的权限编码
    admin_role = db.query(app.models.role.Role).filter_by(id=admin_role_id).first()
    existing_permission_ids = [p.id for p in admin_role.permissions]
    
    # 为管理员分配所有权限
    for permission in permissions:
        if permission.id not in existing_permission_ids:
            try:
                PermissionService.assign_permission_to_role(db, admin_role_id, permission.id)
            except Exception:
                # 如果已分配，忽略错误
                pass
    print(f"\t为管理员角色分配所有权限")

def assign_basic_permissions(db, user_role_id, operator_role_id):
    """为普通用户和运维人员分配基本权限"""
    # 为普通用户分配查询权限
    query_permissions = db.query(app.models.permission.Permission).filter(
        app.models.permission.Permission.code.like('%:query')
    ).all()
    
    for permission in query_permissions:
        try:
            PermissionService.assign_permission_to_role(db, user_role_id, permission.id)
        except Exception:
            # 忽略已分配错误
            pass
    
    # 为运维人员分配监控相关权限
    monitor_permissions = db.query(app.models.permission.Permission).filter(
        app.models.permission.Permission.code.like('monitor:%')
    ).all()
    
    for permission in monitor_permissions:
        try:
            PermissionService.assign_permission_to_role(db, operator_role_id, permission.id)
        except Exception:
            # 忽略已分配错误
            pass
            
    print(f"\t为普通用户和运维人员分配基本权限")

if __name__ == "__main__":
    init_database()
    init_data()
